<script setup lang="ts">
import { ref, reactive, onMounted, onUnmounted, nextTick } from "vue";
import { getProjectList, getReport, downloadReport, getCreater } from "@/api/file";
import { downloadFileWithBuffer } from "@/utils/download";
import { ElMessage } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";

defineOptions({
  name: "report"
});
const createrName = ref("");
const projectList = ref([]);
const activeName = ref("first");
const currentPage = ref(1);
const form = ref({
  projectName: "",
});
const pageUrl = ref<{ report: string, history: string[] }>({
  report: "",
  history: []
});
const ruleFormRef = ref<FormInstance>();
const rules = reactive<FormRules>({
  projectName: [{ required: true, message: "请选择项目", trigger: "blur" }],
});
const windowHeight = ref(window.innerHeight);
const reflesh = ref(true);
const loading = ref(false);

// 更新窗口高度的函数
const updateWindowHeight = () => {
  windowHeight.value = window.innerHeight;
};

// 获取项目列表
const getList = async () => {
  try {
    const res = await getProjectList();
    if (res.success) {
      projectList.value = res.data;
    } else {
      ElMessage.error(res.msg);
    }
  } catch (error) {
    ElMessage.error(error);
  }
};
const getCreaterInfo = async () => {
  try {
    const res = await getCreater({ projectName: form.value.projectName });
    if (res.success) {
      createrName.value = res.data;
    } else {
      ElMessage.error(res.msg);
    }
  } catch (error) {
    ElMessage.error(error);
  }
};
// 查询报告
const checkReport = async () => {
  if (!ruleFormRef.value) return;
  await ruleFormRef.value.validate();
  try {
    sessionStorage.setItem("reportProjectName", form.value.projectName);
    const res = await getReport(form.value);
    if (res.success) {
      // 添加时间戳作为查询参数，确保每次请求都有不同的URL
      const timestamp = new Date().getTime();
      pageUrl.value = {
        ...res.data,
        report: `${res.data.report}?timestamp=${timestamp}`,
        history: res.data.history.map(url => `${url}?timestamp=${timestamp}`)
      };
      reflesh.value = false;
      nextTick(() => {
        reflesh.value = true;
      });
    } else {
      ElMessage.error(res.msg);
      pageUrl.value = {
        report: "",
        history: []
      };
    }
  } catch (error) {
    ElMessage.error(error);
    pageUrl.value = {
      report: "",
      history: []
    };
  }
};

const handleChange = (value: string) => {
  getCreaterInfo()
}

const handleClick = () => {

}

const handleDownload = async () => {
  try {
    loading.value = true;
    let reportDirs = pageUrl.value.history.map(item => item.split('/').pop())
    let reportDir = activeName.value == 'first' ? 'report' : reportDirs[currentPage.value - 1]
    // 去掉时间戳
    const timestampIndex = reportDir.indexOf('?');
    if (timestampIndex !== -1) {
      reportDir = reportDir.substring(0, timestampIndex); // 截取到?之前的部分
    }
    const res = await downloadReport({
      projectName: form.value.projectName,
      reportDir: reportDir
    });
    loading.value = false;
    downloadFileWithBuffer(res, reportDir, res.type);
  } catch (error) {
    loading.value = false;
    ElMessage.error(error);
  }
};


const handleCurrentChange = (value: number) => {
  console.log("🚀 ~ handleCurrentChange ~ value:", value)
  currentPage.value = value
  reflesh.value = false;
  nextTick(() => {
    reflesh.value = true;
  });
}

onMounted(async () => {
  window.addEventListener("resize", updateWindowHeight);
  await getList();
  let session = sessionStorage.getItem('reportProjectName')
  if (projectList.value.includes(session)) {
    form.value.projectName = session
    checkReport();
    getCreaterInfo();
  }
});

onUnmounted(() => {
  window.removeEventListener("resize", updateWindowHeight);
});
</script>

<template>
  <el-card class="box-card" v-loading="loading">
    <template #header>
      <div class="card-header">
        <span>查询报告</span>
      </div>
    </template>
    <div>
      <el-form ref="ruleFormRef" :model="form" label-width="120px" :rules="rules" :inline="true">
        <!-- <div class="flex  items-center "> -->
        <el-form-item label="项目名" prop="projectName">
          <el-select v-model="form.projectName" placeholder="请选择项目" @change="handleChange" filterable>
            <el-option v-for="item in projectList" :key="item" :label="item" :value="item" />
          </el-select>
        </el-form-item>
        <el-form-item label="创建人"><el-input v-model="createrName" clearable disabled />
        </el-form-item>
        <!-- </div> -->

      </el-form>
    </div>
    <div class="form-footer">
      <el-button v-if="pageUrl.report" type="primary" @click="handleDownload"> 下载报告 </el-button>
      <el-button type="primary" @click="checkReport"> 查询报告 </el-button>
    </div>
    <div class="embed-container" v-if="pageUrl.report || pageUrl.history.length !== 0">
      <el-tabs v-model="activeName" type="card" class="demo-tabs w-full h-full" @tab-click="handleClick">
        <el-tab-pane label="报告" name="first" :style="{ height: `${windowHeight - 380}px` }">
          <el-empty v-if="!pageUrl.report" description="暂无数据" />
          <iframe v-if="reflesh" :src="pageUrl.report" frameborder="0" allowfullscreen style="width: 100%; height: 100%">
          </iframe>
        </el-tab-pane>
        <el-tab-pane label="历史版本" name="second" :style="{ height: `${windowHeight - 380}px` }">
          <el-empty v-if="pageUrl.history.length === 0" description="暂无数据" />
          <iframe v-if="reflesh" :src="pageUrl.history[currentPage - 1]" frameborder="0" allowfullscreen
            :style="{ width: '100%', height: `${windowHeight - 420}px`, marginBottom: '8px' }">
          </iframe>
          <el-pagination background layout="prev, pager, next" :total="pageUrl.history.length" :default-page-size="1"
            :current-page="currentPage" @update:current-page="handleCurrentChange" />
        </el-tab-pane>
      </el-tabs>
    </div>
    <el-empty v-else description="暂无数据" />
  </el-card>
</template>

<style lang="scss" scoped>
.card-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-weight: 600;
}

.form-footer {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 20px;
}

.embed-container {
  width: 100%;
  border: none;
  /* 根据需要可移除边框 */
}


.create-item {
  padding-left: 20px;
  margin-bottom: 0;
}
</style>
